package scheduleCourse;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Solution {
    public int scheduleCourse(int[][] courses) {
        // 贪心 + 优先级队列
        Arrays.sort(courses, (o1, o2) -> o1[1] - o2[1]);
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((o1, o2) -> o2 - o1);
        int curTime = 0;
        for (int i = 0; i < courses.length; i++) {
            if(curTime + courses[i][0] <= courses[i][1]) {
                // 表示可以选择这门课
                curTime += courses[i][0];
                priorityQueue.add(courses[i][0]);
            } else {
                // 如果不能选
                if(priorityQueue.peek()>courses[i][0]) {
                    curTime -= priorityQueue.poll();
                    priorityQueue.add(courses[i][0]);
                    curTime += courses[i][0];
                }
            }
        }
        return priorityQueue.size();
    }
}
